package com.zr.inquiry.service.impl;

import com.zr.enumvo.CurrencyCodeEnum;
import com.zr.enumvo.IsTaxEnum;
import com.zr.enumvo.TypeEnum;
import com.zr.inquiry.mapper.InquiryMapper;
import com.zr.inquiry.model.*;
import com.zr.inquiry.service.InquiryService;
import com.zr.planclass.model.PlanClassAddVo;
import com.zr.planclass.util.ResultBuilderVo;
import com.zr.planclass.util.ResultVo;
import com.zr.util.AllRecords;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.io.InputStream;
import java.util.*;

/**
 * Created by lenovo on 2019/12/26.
 */
@Service
public class InquiryServiceImpl implements InquiryService{
    @Autowired
    private InquiryMapper inquiryMapper;

   @Override
    public ResultVo queryPage(MaterialSelectVo materialSelectVo) {
        AllRecords allRecords = new AllRecords();
        //根据条件查询总条数
        int count = inquiryMapper.queryMaterialCount(materialSelectVo);
        //根据条件查询数据
        List<InquiryVo> inquiryVoList = inquiryMapper.queryMaterialData(materialSelectVo);
       System.out.println("aaaaaaaaaaaa"+inquiryVoList);
        allRecords.setPageIndex(materialSelectVo.getPageIndex());
        allRecords.setPageSize(materialSelectVo.getPageSize());
        allRecords.setTotalNumber(count);
        allRecords.setDataList(inquiryVoList);
        allRecords.resetTotalNumber(count);
        return ResultBuilderVo.success(allRecords);
    }
    @Override
    public ResultVo queryByLegalPerson(Integer legalPersonId) {
       List<SupplierVo> supplierVoList= inquiryMapper.queryByLegalPerson(legalPersonId);
       return ResultBuilderVo.success(supplierVoList);
    }

    @Override
    public ResultVo searchPartnerPage(SupplierSelectVo supplierSelectVo) {
        AllRecords allRecords = new AllRecords();
        //根据条件查询总条数
        int count = inquiryMapper.queryPartnerCount(supplierSelectVo);
        //根据条件查询数据
        List<SupplierVo> inquiryVoList = inquiryMapper.queryPartnerData(supplierSelectVo);
        allRecords.setPageIndex(supplierSelectVo.getPageIndex());
        allRecords.setPageSize(supplierSelectVo.getPageSize());
        allRecords.setTotalNumber(count);
        allRecords.setDataList(inquiryVoList);
        allRecords.resetTotalNumber(count);
        return ResultBuilderVo.success(allRecords);

    }
    @Override
    public ResultVo inquiryList(InquiryServiceVo inquiryServiceVo) {
        List<InquiryVo> list = inquiryMapper.queryAllInquiry(inquiryServiceVo);
        int count = inquiryMapper.queryAllInquiryCount(inquiryServiceVo);

        AllRecords allRecords = new AllRecords();
        allRecords.setDataList(list);
        allRecords.setPageSize(inquiryServiceVo.getPageSize());
        allRecords.setPageIndex(inquiryServiceVo.getPageIndex());
        allRecords.setTotalNumber(count); //总共的条数
        allRecords.resetTotalNumber(count); //计算总页数
        return ResultBuilderVo.success(allRecords);
    }
    /*修改查看*/
    @Override
    public ResultVo see(String requestForQuotationId) {
        List<InquiryVo> inquiryVoList = new ArrayList<>();
        //根据单号查询询价单信息
        InquiryVo inquiryVo = inquiryMapper.queryInquiryByForQquotationId(requestForQuotationId);
        inquiryVo.setTypeName(TypeEnum.getName(inquiryVo.getType()));
        inquiryVo.setIsTaxName(IsTaxEnum.getName(inquiryVo.getIsTax()));
        inquiryVo.setCurrencyCodeName(CurrencyCodeEnum.getName(inquiryVo.getCurrencyCode()));
        //根据询价单id查询备件明细信息
        List<InquirySpareCodeVo> materialVoList = inquiryMapper.querySpareByInquoryId(inquiryVo.getId());
        //根据询价单id查询供应商信息
        List<InquirySupplierVo> supplierVoList = inquiryMapper.querySupplierByInquoryId(inquiryVo.getId());
        inquiryVo.setInquiryDetailsList(materialVoList);
        inquiryVo.setSupplierDetailsList(supplierVoList);
        inquiryVoList.add(inquiryVo);
        return ResultBuilderVo.success(inquiryVoList);


    }

    @Override
    public ResultVo update(@Valid InquiryAddVo inquiryAddVo) {
        //验证单号是否存在
        String requestForQuotationId = inquiryAddVo.getRequestForQuotationId();
        if (!requestForQuotationId.isEmpty()){
            return ResultBuilderVo.success(requestForQuotationId);
        }
        ResultVo resultVo = validateInquiry(inquiryAddVo);
        if (!resultVo.getSuccess()){
            return resultVo;
        }
        ResultVo resultVo1 = validateInquiry2(inquiryAddVo);
        if (!resultVo1.getSuccess()){
            return resultVo1;
        }
        ResultVo resultVo2 = validateInquiry3(inquiryAddVo);
        if (!resultVo2.getSuccess()){
            return resultVo2;
        }
        ResultVo resultVo3 = validateInquiry4(inquiryAddVo);
        if (!resultVo3.getSuccess()){
            return resultVo3;
        }
        InquiryVo inquiryVo = new InquiryVo();
        BeanUtils.copyProperties(inquiryAddVo,inquiryVo);
        Date nowDate = new Date();
        inquiryVo.setUpdateTime(nowDate);
        inquiryVo.setUpdateName("团团");
        //入库主表
        inquiryMapper.updateTotal(inquiryVo);
        for (InquirySpareCodeVo inquirySpareCodeVo :inquiryVo.getInquiryDetailsList()){
            inquirySpareCodeVo.setInquiryId(inquiryVo.getId());
        }
        inquiryMapper.deleteBySpareDetailInquirtId(inquiryVo.getId());
        inquiryMapper.insertSpareDetail(inquiryVo.getInquiryDetailsList());
        for (InquirySupplierVo inquirySupplierVo :inquiryVo.getSupplierDetailsList()){
            inquirySupplierVo.setInquiryId(inquiryVo.getId());
        }
        inquiryMapper.deleteBySupplierDetailInquirtId(inquiryVo.getId());
        inquiryMapper.insertSupplierDetail(inquiryVo.getSupplierDetailsList());
        return ResultBuilderVo.success();

    }
/*
   @Override
    public ResultVo importInquiryy(MultipartFile file) throws Exception {
        InputStream inputStream = file.getInputStream();
        if (!file.getOriginalFilename().contains("xlsx")){
            return  ResultBuilderVo.error("导入模板版本不正确! 仅支持2007版本的excel版本!");

        }
        poiRead(file);

    return null;

    }

    public ResultVo poiRead(MultipartFile file)throws Exception {
        XSSFWorkbook workbook = new XSSFWorkbook(file.getInputStream());
        //获取单元格中的信息,at0是获取sheet1中的数据;
        XSSFSheet sheet = workbook.getSheetAt(0);
        //验证第一列第一行的表格标头信息是否为"询价单导入",如果不是,提示模板错误
        if (!String.valueOf(sheet.getRow(sheet.getFirstRowNum()).getCell(0)).equals("询价单导入模板")){
            return ResultBuilderVo.error("模板错误,请检查模板!");
        }
        List<QuotationSpareCodeVo> inquirySpareDatailVoList = new ArrayList<>();
        //遍历excel表格中的所有数据，从第五行开始读取，没有数据时终止遍历。
        for (int i = sheet.getFirstRowNum() + 6; i <= sheet.getLastRowNum(); i++) {
            //读取每一行的数据
            XSSFRow xssfRow = sheet.getRow(i);
            if(xssfRow!=null) {
                QuotationSpareCodeVo planClassAddVo = new QuotationSpareCodeVo();
                planClassAddVo.setSpareCoding(String.valueOf(xssfRow.getCell(1)));
                planClassAddVo.setSpareName(String.valueOf(xssfRow.getCell(2)));
                planClassAddVo.setMeasurementUnit(String.valueOf(xssfRow.getCell(3)));
                planClassAddVo.setCurrencyName(String.valueOf(xssfRow.getCell(4)));
                planClassAddVo.setDeliveryCycle(Integer.parseInt(String.valueOf(xssfRow.getCell(5))));
                planClassAddVo.setInquiryQty(Integer.parseInt(String.valueOf(xssfRow.getCell(6))));
                inquirySpareDatailVoList.add(planClassAddVo);


            }

            }
            return ResultBuilderVo.success(inquirySpareDatailVoList);
    }*/
    /*if (!String.valueOf(xssfRow.getCell(1)).equals("")
                        ||!String.valueOf(xssfRow.getCell(2)).equals("")
                        ||!String.valueOf(xssfRow.getCell(3)).equals("")){*/
    //把每一行的数据放入到实体类中
   /* PlanClassAddVo inquiryImportVo = build(xssfRow);
    //把实体类中的数据放入到list集合中
                    inquirySpareDatailVoList.add(inquiryImportVo);*/



    /*询价新增保存接口*/
   @Override
   @Transactional
    /*
        验证询价类型、询价币别、
        是否含税、询价开始日期是否在结束日期之前
        5.验证备件明细不能重复0
        6.验证供应商明细不能重复
        3.验证备件明细不能为空
        4.验证供应商明细不能为空
        7.验证备件是否都存在
        8.验证供应商是否都存在
        9.验证法人是否存在
        1.验证每个备件必须要有可以生产他的供应商
        2.验证每个供应商一定有一个它可以生产的备件
       */
    public ResultVo add(@Valid InquiryAddVo inquiryAddVo) {
        ResultVo resultVo = validateInquiry(inquiryAddVo);
        if (!resultVo.getSuccess()){
            return resultVo;

        }
        ResultVo resultVo1 = validateInquiry2(inquiryAddVo);
        if (!resultVo1.getSuccess()){
            return resultVo1;
        }
        ResultVo resultVo2 = validateInquiry3(inquiryAddVo);
        if (!resultVo2.getSuccess()){
            return resultVo2;
        }
        ResultVo resultVo3 = validateInquiry4(inquiryAddVo);
        if (!resultVo3.getSuccess()){
            return resultVo3;
        }
        InquiryVo inquiryVo = new InquiryVo();
       BeanUtils.copyProperties(inquiryAddVo,inquiryVo);
       inquiryVo.setRequestForQuotationId(UUID.randomUUID().toString());
       Date nowDate = new Date();
       inquiryVo.setCreateTime(nowDate);
       inquiryVo.setCreatorName("林铮铮");
       inquiryVo.setUpdateTime(nowDate);
       inquiryVo.setUpdateName("林铮铮");
       //入库主表
       inquiryMapper.inserTotal(inquiryVo);
       for (InquirySpareCodeVo inquirySpareCodeVo :inquiryVo.getInquiryDetailsList()){
           inquirySpareCodeVo.setInquiryId(inquiryVo.getId());
       }
       inquiryMapper.insertSpareDetail(inquiryVo.getInquiryDetailsList());
       for (InquirySupplierVo inquirySupplierVo : inquiryVo.getSupplierDetailsList()){
           inquirySupplierVo.setInquiryId(inquiryVo.getId());
       }
       inquiryMapper.insertSupplierDatail(inquiryVo.getSupplierDetailsList());
       return ResultBuilderVo.success();

   }




    public ResultVo validateInquiry4(InquiryAddVo inquiryAddVo){
          /*8.验证备件是否有可以生产的供应商
        14.验证供应商是否存在可以生产他的备件*/
        List<InquirySpareCodeVo> inquirySpareCodeVoList = inquiryAddVo.getInquiryDetailsList();
        List<InquirySupplierVo> inquirySupplierVoList = inquiryAddVo.getSupplierDetailsList();
        //前端传过来的供应商集合
        List<String> supplierCodeList = new ArrayList<>();
        for (InquirySupplierVo inquirySupplierVo:inquirySupplierVoList){
            supplierCodeList.add(inquirySupplierVo.getVendorCode());
        }
        List<String> codeList = new ArrayList<>();
        for (InquirySpareCodeVo inquirySpareCodeVo: inquirySpareCodeVoList){
            //根据每个备件查询能被那些供应商生产

            codeList.add(inquirySpareCodeVo.getSpareCoding());
        }
        //根据多个备件集合查询中间表信息，查看这些备件都有哪些供应商生产。
        List<InquirySpareSupplierVo> inquirySpareSupplierVoList =  inquiryMapper.querySpareSupplier(codeList);
        for (String code:codeList){
            //存放的就是每个备件的供应商
            List<String> returnSuppliserCodeList = new ArrayList<>();
            for (InquirySpareSupplierVo inquirySpareSupplierVo:inquirySpareSupplierVoList){
                if (code.equals(inquirySpareSupplierVo.getSpareCoding())){
                    returnSuppliserCodeList.add(inquirySpareSupplierVo.getVendorCode());
                }
            }
            //true不存在交集  false 代表存在交集
            if (Collections.disjoint(supplierCodeList,returnSuppliserCodeList)){
                return ResultBuilderVo.error("备件"+code+"没有合法的供应商，它合法的供应商是"+returnSuppliserCodeList);
            }
        }
        return ResultBuilderVo.success();
    }


    public ResultVo validateInquiry3(InquiryAddVo inquiryAddVo){

        // 1.验证法人是否存在
        int count = inquiryMapper.queryLegalPersonById(inquiryAddVo.getLegalPersonId());
        if (count<=0){
            return ResultBuilderVo.error("法人信息不存在！");
        }
        List<String> codeList = new ArrayList<>();
        for (InquirySpareCodeVo inquirySpareCodeVo:inquiryAddVo.getInquiryDetailsList()){
            codeList.add(inquirySpareCodeVo.getSpareCoding());
        }
        List<String> returnCodeList =  inquiryMapper.querySpareByCodeList(codeList);
        if (codeList.size()!=returnCodeList.size()){
            return ResultBuilderVo.error("请检查，存在不合法的备件！");
        }
        codeList.removeAll(returnCodeList);
        if (!codeList.isEmpty()){
            return ResultBuilderVo.error("不存在的备件编码为："+codeList);
        }
        return ResultBuilderVo.success();
    }

    public ResultVo validateInquiry2(InquiryAddVo inquiryAddVo){
        //所有的备件信息！
        List<String> spareCodeList = new ArrayList<>();
        //取出了前端传过来的备件信息
        List<InquirySpareCodeVo> inquirySpareCodeVoList = inquiryAddVo.getInquiryDetailsList();
        //遍历所有数据把编码取出来放入到集合中
        for (InquirySpareCodeVo inquirySpareCodeVo:inquirySpareCodeVoList){
            spareCodeList.add(inquirySpareCodeVo.getSpareCoding());
        }
        Set<String> setSpareCode = new HashSet<>(spareCodeList);
        if (spareCodeList.size()!=setSpareCode.size()){
            return ResultBuilderVo.error("存在重复的备件编码！");
        }
        List<String> codeList = new ArrayList<>();
        List<String> chognfuList = new ArrayList<>();
        for (String code :spareCodeList){
            if (codeList.contains(code)){
                //里面存放重复的数据
                chognfuList.add(code);
            }else {
                codeList.add(code);
            }
        }
        if (!chognfuList.isEmpty()){
            return ResultBuilderVo.error("存在重复的备件信息，重复的备件信息为："+chognfuList);
        }
        return ResultBuilderVo.success();

    }



    public ResultVo validateInquiry(InquiryAddVo inquiryAddVo) {

        /*验证询价类型、询价币别、
        是否含税、询价开始日期是否在结束日期之前*/
        if (StringUtils.isEmpty(TypeEnum.getName(inquiryAddVo.getType()))){
            return ResultBuilderVo.error("询价类型不存在！");
        }
       if (StringUtils.isEmpty(CurrencyCodeEnum.getName(inquiryAddVo.getCurrencyCode()))){
            return ResultBuilderVo.error("询价币别不存在");
       }
       if (StringUtils.isEmpty(IsTaxEnum.getName(inquiryAddVo.getCurrencyCode()))){
           return ResultBuilderVo.error("询价是否含税类型不存在");
       }
       int res=inquiryAddVo.getStartTime().compareTo(inquiryAddVo.getEndTime());
       if (res > 0){
            return ResultBuilderVo.error("询价开始日期必须在询价结束日期之前");
       }

        return ResultBuilderVo.success();
    }

}
